import { fetchStatus } from '@/api/global'
import { fetchGetDeadLine, fetchSetDeadLine } from '@/api/sysLog'
import Alert from '@/components/Alert'
import { Modal, Select } from '@kedacom/react-next'
import React, { useEffect, useState } from 'react'
import { StyledWrap } from './style'
import { t } from 'i18next'

const dateOptions = [
	{
		value: 7,
		label: t('7天'),
	},
	{
		value: 15,
		label: t('15天'),
	},
	{
		value: 30,
		label: t('30天'),
	},
	{
		value: 60,
		label: t('60天'),
	},
	{
		value: 90,
		label: t('90天'),
	},
	{
		value: 180,
		label: t('180天'),
	},
]

export interface SaveDateModalProps {
	open: boolean
	setOpen: (val: boolean) => void
	setMinDate: (val: number) => void
}

export default function SaveDateModal(props: SaveDateModalProps) {
	const { open, setOpen, setMinDate } = props
	const [deadLine, setDeadLine] = useState(7)

	useEffect(() => {
		if (open) {
			fetchGetDeadLine().then((res) => {
				if (res) {
					setDeadLine(res)
					setMinDate(res)
				} else {
					Alert(t('操作失败'))
				}
			})
		}
	}, [open])

	const handleOK = () => {
		fetchStatus(() =>
			fetchSetDeadLine(deadLine).then((res) => {
				if (res.success) {
					setMinDate(deadLine)
					Alert(t('操作成功'))
				} else {
					Alert(t('操作失败'))
				}
			})
		)
		setOpen(false)
	}

	return (
		<Modal
			className="save-date-modal"
			open={open}
			title={t('保存期限设置')}
			width={400}
			height={260}
			onOk={handleOK}
			onCancel={() => setOpen(false)}
			okText={t('确定')}
			cancelText={t('取消')}
		>
			<StyledWrap>
				<span className="label">{t('期限选择')}</span>
				<Select
					width={200}
					panelPreventOverflow={false}
					options={dateOptions}
					value={deadLine}
					onChange={(e, val) => setDeadLine(val)}
				/>
			</StyledWrap>
		</Modal>
	)
}
